<?php
namespace App\Controller;

use lib\View;
use App\Model\Gallery;

class ImageController
{
    public function edit()
    {
        $gid = $this->input('g');
        $id = $this->input('m');

        $gallery = Gallery::find(['id' => $gid]);

        $image = null;
        foreach ($gallery->imageCollection as $img) {
            if ($img->id === $id) {
                $image = $img;
                break;
            }
        }

        return new View('image/edit', ['image' => $image]);
    }

    public function update()
    {
        $gid = $this->input('g');
        $id = $this->input('m');

        $title = $this->input('title');
        $description = $this->input('description');

        $gallery = Gallery::find(['id' => $gid]);

        $image = null;
        $imageCollection = $gallery->imageCollection;
        for ($i = 0; $i < count($imageCollection); $i++) {
            if ($imageCollection[$i]->id === $id) {
                $imageCollection[$i]->title = $title;
                $imageCollection[$i]->description = $description;
                break;
            }
        }
        $gallery->imageCollection = $imageCollection;
        $gallery->save();
        header('Location:' . url('gallery/detail', ['id' => $gid]));
    }

    public function destroy()
    {
        return '此处执行删除图片的操作';
    }

    private function input($name)
    {
        return htmlspecialchars(stripslashes($_REQUEST[$name]));
    }
}